package com.b.config;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import co.elastic.clients.util.ContentType;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.impl.nio.reactor.IOReactorConfig;
import org.apache.http.message.BasicHeader;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;

import java.io.IOException;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

@Configuration
public class ElasticsearchConfig {

    private final String esUrl = "192.168.70.232"; // 统一配置
    private final int esPort = 9200;

    private RestClient restClient;
    private ElasticsearchTransport transport;

    @Bean
    public RestHighLevelClient restHighLevelClient() {
        return new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost(esUrl, esPort, "http")
                )
        );
    }

    @Bean(name = "elasticsearchClient")
    public ElasticsearchClient elasticsearchClient() {
        restClient = RestClient.builder(
                new HttpHost(esUrl, esPort)
        ).setRequestConfigCallback(
                requestConfigBuilder -> requestConfigBuilder
                        .setConnectTimeout(90000000)
                        .setSocketTimeout(90000000)
        ).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder
                .setKeepAliveStrategy((httpResponse, httpContext) -> TimeUnit.MINUTES.toMillis(3))
                .setDefaultIOReactorConfig(IOReactorConfig.custom().setSoKeepAlive(true).build())
                .setDefaultHeaders(
                        Collections.singletonList(new BasicHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON))
                )
                .addInterceptorLast((HttpResponseInterceptor) (response, context)
                        -> response.addHeader("X-Elastic-Product", "Elasticsearch"))).build();

        transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper()
        );
        return new ElasticsearchClient(transport);
    }

    // 可选：关闭资源
    public void close() {
        try {
            if (transport != null) {
                transport.close();
            }
            if (restClient != null) {
                restClient.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}